package com.zm.campus.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.zm.campus.pojo.RespBean;
import com.zm.campus.pojo.RespBeanEnum;
import com.zm.campus.pojo.User;
import com.zm.campus.dao.UserMapper;
import com.zm.campus.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.zm.campus.util.AssertUtil;
import com.zm.campus.util.PhoneUtil;
import com.zm.campus.vo.BaseUserInfo;
import com.zm.campus.vo.LoginReturnVo;
import com.zm.campus.vo.LoginVo;
import com.zm.campus.vo.UserInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zm
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;


    //根据token从redis中获取当前登录用户的LoginReturnVo
    @Override
    public RespBean getNowUserInfo(String token) {

        LoginReturnVo loginReturnVo =(LoginReturnVo) redisTemplate.opsForValue().get("user:" + token);
        AssertUtil.isTrue(StringUtils.isEmpty(token)||loginReturnVo==null, RespBeanEnum.NoLogin);//用户未登录
        return RespBean.success(loginReturnVo);
    }

    //根据用户id获取用户个人信息
    @Override
    public RespBean getUserById(String userId) {
        UserInfoVo user = userMapper.queryUserById(userId);
        AssertUtil.isTrue(user==null,RespBeanEnum.ReleaseUserNull);//当前用户不存在
        System.out.println(user);
        return RespBean.success(user);
    }

    //更新用户头像
    @Transactional
    @Override
    public RespBean updateAvatar(MultipartFile headImgeFile, String userId) throws IOException {
        User user = userMapper.selectById(userId);
        AssertUtil.isTrue(user==null,RespBeanEnum.ReleaseUserNull);
        AssertUtil.isTrue(user.getAvatar().equals(headImgeFile.getOriginalFilename()),RespBeanEnum.AvatarIsExist);//头像相同未改变
        checkImageType(headImgeFile);
        user.setAvatar(headImgeFile.getOriginalFilename());//设置的是文件的全名，包括拓展名
        AssertUtil.isTrue(userMapper.updateById(user)!=1,RespBeanEnum.UpdateError);
        return RespBean.success();
    }

    //检查图片格式
    public void checkImageType(MultipartFile headImgeFile) throws IOException {
        AssertUtil.isTrue(headImgeFile.getSize()/(1024*1024)>1.5,RespBeanEnum.AvatarToBigger);//头像超1.5M
        AssertUtil.isTrue(!headImgeFile.getContentType().equals("image/jpeg")&&
                !headImgeFile.getContentType().equals("image/png")&&
                !headImgeFile.getContentType().equals("image/jpg"),RespBeanEnum.AvatarTypeError);
        String filePath ="C:\\Users\\PC\\Desktop\\便捷校园图片\\";//图片存放的位置
        //先判断文件夹是否存在
        File dir = new File(filePath);
        if (!dir .exists()  && !dir.isDirectory()){
            dir .mkdir();//不存在目录则创建
        }
        //判断该文件夹是否已经存在该文件了:
        File file = new File(filePath+headImgeFile.getOriginalFilename());
        if (!file.exists()) {//不存在则创建
            headImgeFile.transferTo(file);//把文件保持到指定路径中
        }
    }

    @Transactional
    //完善个人信息
    @Override
    public RespBean updateUserInfo(UserInfoVo userInfoVo) {
        User user = userMapper.selectById(userInfoVo.getId());//查看这个用户是否存在
        AssertUtil.isTrue(StringUtils.isEmpty(userInfoVo.getId())||user==null,RespBeanEnum.ReleaseUserNull );
        AssertUtil.isTrue(!PhoneUtil.isMobile(userInfoVo.getPhone()),RespBeanEnum.PhoneIncorrect);
        AssertUtil.isTrue(!PhoneUtil.checkEmaile(userInfoVo.getEmail()),RespBeanEnum.EmailIncorrect);
        AssertUtil.isTrue(userInfoVo.getAge()==null|| userInfoVo.getAge()<10||userInfoVo.getAge()>100,RespBeanEnum.UserAgeError);
        AssertUtil.isTrue(StringUtils.isEmpty(userInfoVo.getDepartment()),RespBeanEnum.SelectedDepart);
        if (StringUtils.isNotEmpty(userInfoVo.getPetName())){
            user.setPetName(userInfoVo.getPetName());
        }
        user.setDepartment(userInfoVo.getDepartment());
        user.setEmail(userInfoVo.getEmail());
        user.setAge(userInfoVo.getAge());
        user.setPhone(userInfoVo.getPhone());
        user.setClasses(userInfoVo.getClasses());
        AssertUtil.isTrue(userMapper.updateById(user)!=1,RespBeanEnum.UpdateError);
        return RespBean.success();
    }

    //更新个性签名
    @Transactional
    @Override
    public RespBean updatePersonSign(String personSign, String userId) {
            AssertUtil.isTrue(StringUtils.isEmpty(personSign.trim()),RespBeanEnum.ParamsIsNull);
            AssertUtil.isTrue(userMapper.selectById(userId)==null,RespBeanEnum.ReleaseUserNull);//查询要修改个性签名的用户是否存在
            AssertUtil.isTrue(userMapper.updatePersonSignByUserId(personSign,userId)!=1,RespBeanEnum.SystemBusy);
            return RespBean.success();
    }

    //超级管理员授权用户获得管理员身份
    @Transactional
    @Override
    public RespBean authUserToAdmin(String supAdmin, String beUserId,String role) {
        AssertUtil.isTrue(StringUtils.isEmpty(supAdmin)||StringUtils.isEmpty(beUserId)||StringUtils.isEmpty(role),RespBeanEnum.ParamsIsNull);
        AssertUtil.isTrue(!supAdmin.equals("superAdmin"),RespBeanEnum.InsufficientAuthority);//权限不足
        User user = userMapper.selectById(beUserId);
        AssertUtil.isTrue(user==null,RespBeanEnum.ReleaseUserNull);
        AssertUtil.isTrue(role.equals(user.getRole()),RespBeanEnum.AuthRoleNotChange);//说明当前用户还是这个角色，未变化
        user.setRole(role);
        AssertUtil.isTrue(userMapper.updateById(user)!=1,RespBeanEnum.UpdateError);
        return RespBean.success();
    }

    @Override
    public RespBean getUserInfoByUid(String userId) {
        AssertUtil.isTrue(StringUtils.isBlank(userId),RespBeanEnum.BIND_ERROR);
        BaseUserInfo baseUserInfo;
        baseUserInfo = (BaseUserInfo)redisTemplate.opsForValue().get("UserInfo=" + userId);//先从缓存中查，没有再从数据库中查
        if (baseUserInfo==null) {
            baseUserInfo = userMapper.getUserInfoByUid(userId);
            redisTemplate.opsForValue().set("UserInfo=" + userId, baseUserInfo, 7, TimeUnit.DAYS);
        }
        return RespBean.success(baseUserInfo);
    }
    //超级管理员授权用户获得管理员身份


}
